import requests
import time
import random

# 配置参数
TARGET_URL = "https://juejin.cn/post/7502278666211557413"  # 掘金文章地址
TOTAL_VISITS = 1000  # 设置总访问次数

def getHeaders():
    user_agent_list = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Safari/605.1.15",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Mobile/15E148 Safari/604.1"
    ]
    
    headers = {
        'User-Agent': random.choice(user_agent_list),
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-User': '?1',
        'Cache-Control': 'max-age=0',
        'Referer': 'https://juejin.cn/',
        'X-Juejin-Src': 'web',
        'Origin': 'https://juejin.cn'
    }
    return headers

def access_article():
    '''访问指定掘金文章页面'''
    session = requests.Session()
    try:
        # 先访问掘金首页获取必要的Cookie
        session.get(
            url='https://juejin.cn',
            headers=getHeaders(),
            timeout=10
        )
        
        # 访问目标页面
        response = session.get(
            url=TARGET_URL,
            headers=getHeaders(),
            timeout=10,
            allow_redirects=True
        )
        
        # 如果响应中包含新的Cookie，更新会话Cookie
        if 'Set-Cookie' in response.headers:
            session.cookies.update(response.cookies)
            
        print(f"访问成功 | 状态码: {response.status_code} | URL: {TARGET_URL}")
        return True
    except Exception as e:
        print(f"访问失败: {str(e)}")
        return False

if __name__ == '__main__':
    print(f"开始访问掘金文章，计划访问 {TOTAL_VISITS} 次...")
    completed_visits = 0
    
    while completed_visits < TOTAL_VISITS:
        print(f"\n=== 当前进度：{completed_visits + 1}/{TOTAL_VISITS} ===")
        if access_article():
            completed_visits += 1
            
        # 固定等待1秒
        if completed_visits < TOTAL_VISITS:
            time.sleep(1)
    
    print("\n✅ 已完成所有计划访问！")




